package com.zkingsoft.zkingbase.model;

import android.util.Log;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.zkingsoft.zkingbase.bean.resp.BaseResp;
import com.zkingsoft.zkingbase.constant.Constant;
import com.zkingsoft.zkingbase.engine.UpdateEngine;
import com.zkingsoft.zkingbase.manager.OkHttpManager;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ytf on 2017/3/6 006.
 * Description: MVP model，主要任务是获取数据
 */

public class BaseModel
{
    public OkHttpManager okManager;
    public Retrofit retrofit;
    public Observable<BaseResp> observable;
    public Disposable dis;
    //自定义client，可以用来设置一些个性化属性，比如缓存等等
    public static OkHttpClient client;
    //默认超时时间10秒
    private static int timeout = 10;

    public BaseModel()
    {
        if(client == null)
        {
            client = new OkHttpClient.Builder()
                    .addInterceptor(new LogInterceptor())
                    .connectTimeout(timeout, TimeUnit.SECONDS)
                    .readTimeout(timeout, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build();
        }
        okManager = OkHttpManager.getInstance();
        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.WEB_BASE)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /***
     * Log,主要记录每次请求的参数及链接
     */
    private class LogInterceptor implements okhttp3.Interceptor
    {

        @Override
        public Response intercept(Chain chain) throws IOException
        {
            Request request = chain.request();
            StringBuilder sb = new StringBuilder();
            sb.append(request.url().toString());
            String method = request.method();
            if ("POST".equals(method))
            {
                if (request.body() instanceof FormBody)
                {
                    sb.append("?");
                    FormBody body = (FormBody) request.body();
                    for (int i = 0; i < body.size(); i++)
                    {
                        sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + "&");
                    }
                    sb.delete(sb.length() - 1, sb.length());
                }
            }
            Log.e("s", "request:" + sb.toString());
            okhttp3.Response response = chain.proceed(chain.request());
            return response;
        }
    }

    /***
     *
     * @param e
     * @return
     */
    public String getFailedString(Throwable e)
    {
        if (e instanceof com.google.gson.JsonParseException)
        {
            return "Json 转换异常";
        } else if (e instanceof ConnectException)
        {
            return "无法连接";
        } else if (e instanceof SocketTimeoutException)
        {
            return "连接超时";
        }
        return "网络异常";
    }

    /***
     * Observable及时取消订阅，防止内存泄漏
     */
    public void dispose()
    {
        if (dis != null && !dis.isDisposed())
        {
            dis.dispose();
        }
    }
}
